<template>
  <el-dialog v-model="dialogData.visible"
             :title="dialogData.title" width="30%" @close="closeDialog">
    <div class="file-container">
      <el-input v-model="filename" />
      <div class="operation-btn">
        <input type="file" @change="changeFile" class="file-chooser">
        <el-button>浏览...</el-button>
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="importData()">
          导入
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">

  import {ref, defineProps, defineEmits } from "vue";
  import { uploadFile } from '../../components/ajax'
  import {ElMessage} from "element-plus";

  const props = defineProps({
    dialogData: Object
  })

  const emits = defineEmits(['searchEvent'])

  const file = ref<File>(null) //这个变量就是来存储当前选择的文件

  const filename = ref("")

  const changeFile = (e) => {
    console.log(e.target.files)
    let files = e.target.files;
    if(files&&files.length === 1){
      filename.value = files[0].name;
      file.value = files[0]
    } else {
      file.value = null;
    }
  }

  const closeDialog = () => {
    props.dialogData.visible = false
  }

  const importData = () =>{
    if(file.value === null){
      ElMessage.error("请选择上传的文件")
      return
    }
    uploadFile(props.dialogData.url, file.value, resp => {
      if(resp.data){
        ElMessage.success("导入成功");
        closeDialog()
        emits('searchEvent')
      } else {
        ElMessage.error("导入失败");
      }
    })
  }
</script>

<style scoped>
  .file-container{
    display: flex;
    flex-direction: row;
  }
  .el-input{
    flex-shrink: 1.0;
    flex-grow: 1.0;
  }
  .operation-btn{
    width: 71px;
    position: relative;
  }

  .file-chooser{
    position: absolute;
    height: 32px;
    width: 71px;
    opacity: 0;
  }
</style>
